package com.study.talk.netty

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import com.study.talk.R
import com.study.talk.data.net.OkHttp
import com.study.talk.di.AppModule

class NettyService : Service() {
    companion object {
        private const val TAG = "NettyService"
    }

    override fun onCreate() {
        super.onCreate()
        setNotificationAndForeground()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        NettyClient.start(AppModule.getIpAddress(), AppModule.getNettyPort())
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onDestroy() {
        Log.e(TAG, "onDestroy: 服务被杀")
        NettyClient.close()
        super.onDestroy()
    }


    //设置前台服务通知
    private fun setNotificationAndForeground() {
        val channelId = "TALK_ID"
        val notificationChannel =
            NotificationChannel(channelId, "畅聊前台服务", NotificationManager.IMPORTANCE_HIGH)
        notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC //设置前台服务锁屏可见
        (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
            notificationChannel
        )
        val notification = Notification.Builder(this, channelId)
            .setAutoCancel(false) //点击后不会取消
            .setContentText("畅聊正在后台运行")
            .setSmallIcon(R.drawable.app_logo)
            .setOngoing(true)
            .build()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING)
        } else {
            startForeground(1, notification)
        }
    }
}